package com.jr.Assess_java.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author:xhh
 * @email:3231954428@qq.com
 * @desc: 该类用于封装网络请求的代码，返回请求数据
 * @datatime:2021/12/7 11:36
 */
public class HttpUtils {
    /**
     * 该函数用于实现get请求
     * path：资源路径
     * return:返回请求的结果
     * */
    public static String get(String path){
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        //最开始的行
        String line = "";
        //每次读取的累计行
        String result = "";

        //拼接url
        try {
            //URL:统一资源定位
            URL url = new URL(path);
            //连接对象
            URLConnection connection = url.openConnection();
            //连接的动作，发起连接
            connection.connect();
            inputStream = connection.getInputStream();
            //字符流
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            //读取行，直到所有行都读完
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (reader != null){
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
